package com.engine.budget.cmd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.weaver.general.TimeUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.hrm.User;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;

import java.util.*;


/**
 * 业务项目管理平台	业务项目创建项目信息接口
 */
public class WeaReportConditionDemoCmd extends AbstractCommonCommand<Map<String,Object>> {

    public WeaReportConditionDemoCmd(User user, Map<String,Object> params) {
        this.user = user;
        this.params = params;
    }


    /**
     * @param commandContext
     * @return
     */
    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        JSONObject paramsJson = JSONObject.parseObject(JSONObject.toJSONString(params));
        JSONArray paramsArray = paramsJson.getJSONArray("params");
        Iterator<Object> paramsArrayIterator = paramsArray.iterator();

        HashMap<String, Object> restMap = new HashMap<>();
        HashMap<String, Object> result = new HashMap<>();
        result.put("status","0");
        result.put("errorCode","10000");
        result.put("errorMessage",null);

        ArrayList<JSONObject> data = new ArrayList<>();
        while(paramsArrayIterator.hasNext()){
            JSONObject param = (JSONObject) paramsArrayIterator.next();
            //处理jsonObject
            JSONArray projectArray = param.getJSONArray("project");
            Iterator<Object> projectArrayIterator = projectArray.iterator();
            while (projectArrayIterator.hasNext()){
                JSONObject project = (JSONObject) projectArrayIterator.next();
                HashMap<String, Object> map = new HashMap<>();
                map.put("xmbh",project.getString("projectNumber"));
                map.put("xmmc",project.getString("projectName"));
                map.put("zhdw",project.getString("executeDept"));
                map.put("ysnd", TimeUtil.getCurrentDateString());
                map.put("xmlxzjewy",project.getString("projectTotalAmount"));
                map.put("xmzbrmc",project.getString("userName"));
                map.put("qbmchhyjyd",project.getString("signReportName"));
                map.put("xmmblx",project.getString("projectTargetType"));
                map.put("szjyjhzdxm",project.getString("businessPlanName"));
                map.put("szywcp",project.getString("majorProduct"));
                map.put("szyssx","9.2");
                map.put("szdwzdgz",project.getString("jobNumber"));
//                map.put("sqdh",UUID.randomUUID());
                map.put("sqsj",TimeUtil.getCurrentDateString());
                map.put("yszz","技术部企划部统筹");
                map.put("ywxl","9.2");
                map.put("ywlx","9");

                JSONObject ysxmdb = selectUfYSXMDBByProjectNumber(project.getString("projectNumber"));

                map.put("szyssx",ysxmdb.getString("yssx"));

                Integer workflowid = Integer.valueOf(Prop.getPropValue("businessbudgetpz","workflowid4"));
                String newrequestid = Createrequest(workflowid, 1, "项目立项", "1", map);
                if (Integer.valueOf(newrequestid) <= 0){
                    JSONObject resDataJson = new JSONObject();
                    resDataJson.put("result","false");
                    resDataJson.put("msg","立项失败");
                    data.add(resDataJson);
                    continue;
                }

                String tableNameBYWorkflowid = getTableNameBYWorkflowid(workflowid);
                if (Integer.valueOf(newrequestid) > 0){
                    String id = get(newrequestid,tableNameBYWorkflowid);
                    //新增明细
                    ArrayList<String> kmList = new ArrayList<>();
                    kmList.add("项目立项金额:资本化");
                    kmList.add("项目立项金额:系统运营费");
                    kmList.add("项目立项金额:技术开发类费用");
                    kmList.add("项目立项金额:修理维护费");
                    kmList.add("项目立项金额:低值易耗品摊销");
//                kmList.add("事项全周期总预算:资本化");
//                kmList.add("事项全周期总预算:系统运营费");
//                kmList.add("事项全周期总预算:技术开发类费用");
//                kmList.add("事项全周期总预算:修理维护费");
//                kmList.add("事项全周期总预算:低值易耗品摊销");
                    for (String s : kmList) {
                        HashMap<String, String> hashMap = new HashMap<>();
                        hashMap.put("ysnd",TimeUtil.getCurrentDateString());
                        hashMap.put("xmndyswy","0");
                        hashMap.put("mainid",id);
                        if (s.equals("项目立项金额:资本化")){hashMap.put("xmlxzjewy",project.getString("projectCapitalization"));}
                        if (s.equals("项目立项金额:系统运营费")){hashMap.put("xmlxzjewy",project.getString("projectSystemCosts"));}
                        if (s.equals("项目立项金额:技术开发类费用")){hashMap.put("xmlxzjewy",project.getString("projectResearchDev"));}
                        if (s.equals("项目立项金额:修理维护费")){
                            hashMap.put("xmlxzjewy", StringUtils.isEmpty(project.getString("projectRepair")) ? "0" : project.getString("projectRepair"));
                        }
                        if (s.equals("项目立项金额:低值易耗品摊销")){
                            hashMap.put("xmlxzjewy", StringUtils.isEmpty(project.getString("projectLowValue")) ? "0" : project.getString("projectLowValue"));
                        }
//                    if (s.equals("事项全周期总预算:资本化")){hashMap.put("xmlxzjewy","0");}
//                    if (s.equals("事项全周期总预算:系统运营费")){hashMap.put("xmlxzjewy","0");}
//                    if (s.equals("事项全周期总预算:技术开发类费用")){hashMap.put("xmlxzjewy","0");}
//                    if (s.equals("事项全周期总预算:低值易耗品摊销")){hashMap.put("xmlxzjewy","0");}
                        saveDt1(hashMap,s,tableNameBYWorkflowid+"_dt1");
                    }

                    JSONObject resDataJson = new JSONObject();
                    resDataJson.put("result","true");
                    resDataJson.put("msg","立项成功");
                    data.add(resDataJson);
                }
            }
        }
        result.put("data",data);
        restMap.put("result",result);
        return restMap;
    }

    /**
     * 查询项目底表
     * @param projectNumber
     * @return
     */
    public JSONObject selectUfYSXMDBByProjectNumber(String projectNumber){
        String sql = "select * from uf_ysxmdb where xmbm = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, projectNumber);
        JSONObject jsonObject = new JSONObject();
        while (rs.next()){
            jsonObject.put("zxdw",rs.getString("zxdw"));
            jsonObject.put("id",rs.getString("id"));
            jsonObject.put("xmbm",rs.getString("xmbm"));
            jsonObject.put("xmmc",rs.getString("xmmc"));
            jsonObject.put("ywlx",rs.getString("ywlx"));
            jsonObject.put("ywxl",rs.getString("ywxl"));
            jsonObject.put("zz",rs.getString("zz"));
            jsonObject.put("hdnf",rs.getString("hdnf"));
            jsonObject.put("sfgb",rs.getString("sfgb"));
            jsonObject.put("qbmc",rs.getString("qbmc"));
            jsonObject.put("qbzje",rs.getString("qbzje"));
            jsonObject.put("xmzbrgh",rs.getString("xmzbrgh"));
            jsonObject.put("xmzbrmc",rs.getString("xmzbrmc"));
            jsonObject.put("xmqdsj",rs.getString("xmqdsj"));
            jsonObject.put("xmjssj",rs.getString("xmjssj"));
            jsonObject.put("szjyjhzd",rs.getString("szjyjhzd"));
            jsonObject.put("ywxmbm",rs.getString("ywxmbm"));
            jsonObject.put("ywxmmc",rs.getString("ywxmmc"));
            jsonObject.put("ywxmid",rs.getString("ywxmid"));
            jsonObject.put("xmmblx",rs.getString("xmmblx"));
            jsonObject.put("szywcp",rs.getString("szywcp"));
            jsonObject.put("modedatamodifier",rs.getString("modedatamodifier"));
            jsonObject.put("modedatamodifydatetime",rs.getString("modedatamodifydatetime"));
            jsonObject.put("yssx",rs.getString("yssx"));

        }
        return jsonObject;
    }

    /**
     * 方法描述 : 创建流程方法
     *  @param workflowid
     *  @param userid 创建人id
     *  @param title  流程标题
     *  @param IsNextFlow  是否默认流转到下一节点   1 是，0 否
     *  @param map   数据map
     *  @return
     * String
     */
    public String Createrequest(int workflowid,int userid,String title,String IsNextFlow,Map map){
        String newrequestid="";
        RequestInfo req=new RequestInfo();
        req.setCreatorid(userid+"");  //创建人
        req.setWorkflowid(workflowid+"");//流程id
        req.setDescription(title);  //流程标题
        req.setIsNextFlow(IsNextFlow); //是否默认流转到下一节点
        MainTableInfo maintable=new MainTableInfo();

        Set<String> keySet = map.keySet();
        Property[] property = new Property[keySet.size()];
        int i= 0;
        Property p = null;
        for(String key : keySet){
            p = new Property();
            p.setName(key);
            p.setValue(map.get(key).toString());
            property[i] = p;
            i++;
        }

        maintable.setProperty(property);

        req.setMainTableInfo(maintable);
        req.setRequestlevel("0");
        RequestService service=new RequestService();
        try {
            newrequestid=service.createRequest(req);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newrequestid;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }


    /**
     * 根据workflowid查询表名称
     * @param workflowid
     */
    public String getTableNameBYWorkflowid(Integer workflowid){

        String sql = "select t.id workflowid, t2.TABLENAME  from workflow_base t " +
                "left join workflow_bill t2 on t.FORMID = t2.id " +
                "WHERE t.id = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, workflowid);
        String tableName = null;
        while (rs.next()){
            tableName = rs.getString("TABLENAME");
        }
        return tableName;

    }
    public String get(String reqId,String tableName){
//        String tableName = "formtable_main_607_dt1";
        String sql = "select * from "+tableName+" where requestId = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, reqId);
        String id = null;
        while (rs.next()){
            id = rs.getString("id");
        }
        return id;
    }

    public void saveDt1(Map<String,String> map,String km,String tableName){
        String sql = "insert into "+tableName+"(mainid,xmlxzjewy,xmndyswy,ysnd,yskm) values (?,?,?,?,?)";

        ArrayList<String> list = new ArrayList<>();
        list.add(map.get("mainid"));
        list.add(map.get("xmndyswy"));
        list.add(map.get("xmlxzjewy"));
        list.add(map.get("ysnd"));
        list.add(km);
        RecordSet rs = new RecordSet();
        rs.executeUpdate(sql, list);
    }
}
